{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 7 层级索引（hierarchical indexing）（机器学习，深度学习不重要）",
   "id": "987baa6a0775c6a8"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T10:51:58.051904Z",
     "start_time": "2025-01-08T10:51:58.043598Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "# MultiIndex是层级索引，索引类型的一种\n",
    "index1=pd.MultiIndex.from_arrays(\n",
    "    [['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd'],\n",
    "                [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]],\n",
    "    names=['cloth', 'size']\n",
    ")\n",
    "\n",
    "ser_obj=pd.Series(np.random.randn(12), index=index1)\n",
    "print(ser_obj)\n",
    "print(\"-\"*50)\n",
    "\n",
    "print(type(ser_obj)) # Series类型\n",
    "print(type(ser_obj.index)) # MultiIndex类型\n",
    "print(\"-\"*50)\n",
    "\n",
    "print(ser_obj.index) # 层级索引\n",
    "print(\"-\"*50)\n",
    "print(ser_obj.index.levels) # 层级索引的索引值\n",
    "print(\"-\"*50)\n"
   ],
   "id": "696ca7e38abc8e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cloth  size\n",
      "a      0      -1.813760\n",
      "       1      -1.185017\n",
      "       2      -1.174419\n",
      "b      0      -0.624507\n",
      "       1      -2.625160\n",
      "       2       0.707804\n",
      "c      0       0.731622\n",
      "       1       0.807310\n",
      "       2       0.513461\n",
      "d      0      -0.972531\n",
      "       1      -0.552642\n",
      "       2       0.083734\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "<class 'pandas.core.series.Series'>\n",
      "<class 'pandas.core.indexes.multi.MultiIndex'>\n",
      "--------------------------------------------------\n",
      "MultiIndex([('a', 0),\n",
      "            ('a', 1),\n",
      "            ('a', 2),\n",
      "            ('b', 0),\n",
      "            ('b', 1),\n",
      "            ('b', 2),\n",
      "            ('c', 0),\n",
      "            ('c', 1),\n",
      "            ('c', 2),\n",
      "            ('d', 0),\n",
      "            ('d', 1),\n",
      "            ('d', 2)],\n",
      "           names=['cloth', 'size'])\n",
      "--------------------------------------------------\n",
      "[['a', 'b', 'c', 'd'], [0, 1, 2]]\n",
      "--------------------------------------------------\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T10:59:20.506659Z",
     "start_time": "2025-01-08T10:59:20.499990Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 层级索引的使用\n",
    "\n",
    "print(ser_obj['c']) # 取出外层索引为\"c\"的所有数据，取出的是series\n",
    "print(\"-\"*50)\n",
    "print(type(ser_obj['c'])) # 输出类型为series\n",
    "print(\"-\"*50)\n",
    "\n",
    "print(ser_obj.loc[\"a\",2]) # 取出外层索引为\"a\"，内层索引为2的数据\n",
    "print(\"-\"*50)\n",
    "print(type(ser_obj.loc[\"a\",2])) # 输出类型为float\n",
    "print(\"-\"*50)\n",
    "\n",
    "print(ser_obj.loc[:,2])  # 取出所有行的内层索引为2的数据\n",
    "print(\"-\"*50)\n",
    "print(type(ser_obj.loc[:,2])) # 输出类型为series"
   ],
   "id": "116f2019a9f4991d",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "size\n",
      "0    0.731622\n",
      "1    0.807310\n",
      "2    0.513461\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "<class 'pandas.core.series.Series'>\n",
      "--------------------------------------------------\n",
      "-1.1744188081170106\n",
      "--------------------------------------------------\n",
      "<class 'numpy.float64'>\n",
      "--------------------------------------------------\n",
      "cloth\n",
      "a   -1.174419\n",
      "b    0.707804\n",
      "c    0.513461\n",
      "d    0.083734\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "<class 'pandas.core.series.Series'>\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 交换层级",
   "id": "2095555e924540a2"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T11:04:43.580491Z",
     "start_time": "2025-01-08T11:04:43.575057Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# swaplevel()方法可以交换层级索引的位置\n",
    "print(ser_obj.swaplevel())\n",
    "print(\"-\"*50)\n",
    "\n",
    "# swaplevel()方法返回新Series，原Series不变\n",
    "print(ser_obj) \n",
    "print(\"-\"*50)\n"
   ],
   "id": "7786366c45369c9f",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "size  cloth\n",
      "0     a       -1.813760\n",
      "1     a       -1.185017\n",
      "2     a       -1.174419\n",
      "0     b       -0.624507\n",
      "1     b       -2.625160\n",
      "2     b        0.707804\n",
      "0     c        0.731622\n",
      "1     c        0.807310\n",
      "2     c        0.513461\n",
      "0     d       -0.972531\n",
      "1     d       -0.552642\n",
      "2     d        0.083734\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "cloth  size\n",
      "a      0      -1.813760\n",
      "       1      -1.185017\n",
      "       2      -1.174419\n",
      "b      0      -0.624507\n",
      "       1      -2.625160\n",
      "       2       0.707804\n",
      "c      0       0.731622\n",
      "       1       0.807310\n",
      "       2       0.513461\n",
      "d      0      -0.972531\n",
      "       1      -0.552642\n",
      "       2       0.083734\n",
      "dtype: float64\n",
      "--------------------------------------------------\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T11:04:57.634747Z",
     "start_time": "2025-01-08T11:04:57.628507Z"
    }
   },
   "cell_type": "code",
   "source": [
    "ser_obj=ser_obj.swaplevel()\n",
    "print(ser_obj) # 交换层级后，原Series的层级索引交换了\n",
    "print(\"-\"*50)\n",
    "\n",
    "# sort_index()方法可以对层级索引进行排序\n",
    "# sort_index()方法返回新Series，原Series不变\n",
    "# leve=0表示对外层索引进行排序\n",
    "print(ser_obj.sort_index(level=0))"
   ],
   "id": "6634a96a42ceedac",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "size  cloth\n",
      "0     a       -1.813760\n",
      "1     a       -1.185017\n",
      "2     a       -1.174419\n",
      "0     b       -0.624507\n",
      "1     b       -2.625160\n",
      "2     b        0.707804\n",
      "0     c        0.731622\n",
      "1     c        0.807310\n",
      "2     c        0.513461\n",
      "0     d       -0.972531\n",
      "1     d       -0.552642\n",
      "2     d        0.083734\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "size  cloth\n",
      "0     a       -1.813760\n",
      "      b       -0.624507\n",
      "      c        0.731622\n",
      "      d       -0.972531\n",
      "1     a       -1.185017\n",
      "      b       -2.625160\n",
      "      c        0.807310\n",
      "      d       -0.552642\n",
      "2     a       -1.174419\n",
      "      b        0.707804\n",
      "      c        0.513461\n",
      "      d        0.083734\n",
      "dtype: float64\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T11:12:42.110095Z",
     "start_time": "2025-01-08T11:12:42.104495Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# unstack()方法可以将Series转为DataFrame，DataFrame的列名为外层索引，行名为内层索引\n",
    "df_obj=ser_obj.unstack()\n",
    "print(df_obj) \n",
    "print(\"-\"*50)\n",
    "print(type(df_obj)) # DataFrame类型"
   ],
   "id": "2bf3f2626ef45f02",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cloth         a         b         c         d\n",
      "size                                         \n",
      "0     -1.813760 -0.624507  0.731622 -0.972531\n",
      "1     -1.185017 -2.625160  0.807310 -0.552642\n",
      "2     -1.174419  0.707804  0.513461  0.083734\n",
      "--------------------------------------------------\n",
      "<class 'pandas.core.frame.DataFrame'>\n"
     ]
    }
   ],
   "execution_count": 20
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T11:09:40.229750Z",
     "start_time": "2025-01-08T11:09:40.224747Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#对df进行stack，就会把行，列索引进行堆叠，变为series\n",
    "#把列索引放入内层,只能放到内层\n",
    "print(df_obj.stack())"
   ],
   "id": "ac2e84f1aa390725",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "size  cloth\n",
      "0     a       -1.813760\n",
      "      b       -0.624507\n",
      "      c        0.731622\n",
      "      d       -0.972531\n",
      "1     a       -1.185017\n",
      "      b       -2.625160\n",
      "      c        0.807310\n",
      "      d       -0.552642\n",
      "2     a       -1.174419\n",
      "      b        0.707804\n",
      "      c        0.513461\n",
      "      d        0.083734\n",
      "dtype: float64\n"
     ]
    }
   ],
   "execution_count": 18
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
